<template>
	<div>
		<el-row class="tac">
			<el-col :span="4">
				<el-card class="box-card" style="height: 800px;">
					<div>
						<h4>角色名称</h4>
						<el-button type="text" @click="showAdd">添加角色</el-button>
						<el-button type="text" @click="showDel">删除角色</el-button>
					</div>
					<br />
					<div class="setheight_scroller">
					<!--<el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>-->
					<el-tree 
						class="filter-tree " 
						:data="roleDate" 
						:props="defaultProps" 
						node-key="role_key" 
						:expand-on-click-node="false" 
						default-expand-all 
						@current-change="handleClick" 
						ref="tree">
					</el-tree>
					</div>
				</el-card>
			</el-col>
			<el-col  :span="20">
				<el-card class="box-card" style="height: 800px;">
				<el-tabs type="card" tab-position="tabPosition" v-model="activeName" @tab-click="tabClick">
					<el-tab-pane name="first">
						<span slot="label">{{roleName}}用户</span>
						<div>
							<h5 v-if="!seen" style="color: #D2D7DC;">请选择角色</h5>
							<el-button type="text" @click="showAddUser" v-if="seen">添加用户</el-button>
							<el-button type="text" @click="delUser" v-if="seen">删除用户</el-button>
						</div>
						<div style="height: 600px;overflow: auto;">
							<el-checkbox-group v-model="checkedUser">
								<el-checkbox v-for="item in roleUserData" :label="item.user_key" :key="item.user_key">{{ item.user_name }}</el-checkbox>
							</el-checkbox-group>
						</div>
						
					</el-tab-pane>
					<el-tab-pane name="second">
						<span slot="label">{{roleName}}权限</span>
						<div>
							<h5 v-if="!seen" style="color: #D2D7DC;">请选择角色</h5>
							<el-button type="text" @click="showAddPower" v-if="seen">添加权限</el-button>
							<el-button type="text" @click="delPower" v-if="seen">删除权限</el-button>
						</div>
						<br />
						<div>
							<role-according :role-key='roleKey' :role-status="roleStatus" :key="2" @multipleTable="getMultipleTable" @delStatus="getDelStatus" :del-status="delstatus"></role-according>
						</div>
					</el-tab-pane>
				</el-tabs>
				</el-card>
			</el-col>
		</el-row>
		<!--新增界面-->
		<el-dialog :title="text" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="resetForm('addForm')" style="padding-bottom:0;">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm" style="height:240px;">
				<el-form-item label="角色ID" prop="role_id">
					<el-input v-model="addForm.role_id" auto-complete="off" placeholder="请输入角色ID"></el-input>
				</el-form-item>
				<el-form-item label="角色名称" prop="role_name">
					<el-input v-model="addForm.role_name" auto-complete="off" placeholder="请输入角色名称"></el-input>
				</el-form-item>
				<el-form-item label="角色说明" prop="remarks">
					<el-input type="textarea" placeholder="请输入说明" auto-complete="off" :rows="4" v-model="addForm.remarks"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer" style="text-align: left; margin-left:30px;margin-left:80px;">
				<el-button type="primary" @click.native="addSubmit">提交</el-button>
				<el-button @click="resetForm('addForm')">重置</el-button>
			</div>
		</el-dialog>
		<!--新增角色成员-->
		<el-dialog title="添加部门成员" :visible.sync="addUserVisible" width="30%" @close="handleClose">
			<span>选择用户</span>
			<el-select v-model="checkedUser" filterable multiple placeholder="请选择">
				<el-option v-for="item in noRoleUserData" :key="item.user_key" :label="item.user_name" :value="item.user_key">
				</el-option>
			</el-select>
			<span slot="footer" class="dialog-footer">
			    <el-button @click="addUserVisible = false;">取 消</el-button>
			    <el-button type="primary" @click="addUser">确 定</el-button>
			  </span>
		</el-dialog>
		<!-- 新增角色权限 -->
		<el-dialog title="添加权限" :visible.sync="addPowerVisible" width="70%" @close="handleClose">
			<span>选择权限</span>
			<role-according :role-key='roleKey' :role-status="roleStatus" :showButton="true" @addPowerVisible="getAddPowerVisible"  :key="1"></role-according>
		</el-dialog>
	</div>
</template>

<script>
	import { query, apiparas, execute } from '../../api/api';
	import { Cookie } from '../../js/common';
	import roleAccording from './components/roleAccording.vue';
	export default {
		components:{
            roleAccording,
      	},
		data() {
			return {
				powerid: '',
				currentPage: 1,
				pagesize: 10,
				roleDate: [],
				roleStatus:'in',
				PowerTreeData: [],
				roleUserData: [], //部门下的用户
				noRoleUserData: [],
				rolePowerData: [],
				delstatus:false,
				noRolePowerData: [],
				checkedUser: [],
				checkedPower: [],
				multipleTable: [],
				roleKey: '',
				roleName: '',
				p_department_name: '',
				activeName: 'first',
				text: '',
				editId: '',
				addFormVisible: false,
				addUserVisible: false,
				addPowerVisible: false,
				defaultPropsPowerTree: {
					id: 'id',children: 'subs',label: 'tree_name'
				},
				addForm: {
					role_id: '',role_name: '',remarks: ''
				},
				isAddShow: false,
				isEditShow: false,
				editFormVisible: false,
				addFormRules: {
					role_id: [{
							required: true,message: '请输入角色ID',trigger: 'blur'
					},//{ validator: validaePass }
					],
					role_name: [{
							required: true,message: '请输入角色名称',trigger: 'blur'
					},//{ validator: validaePass }
					]
				},
				msg: '',
				filterText: '',
				defaultProps: {
					id: 'role_key',children: 'subs',
					label: function(data, node) {
						return data.role_key + ' -- ' + data.role_name;
					}
				},
			}
		},
		mounted: function() {
			//生命周期
		},
		computed: {
			//计算属性
			company_key() {
				let company_key = Cookie.Get("company_key");
				return company_key;
			},
			seen() {
				if(this.roleKey === '') {
					return false;
				} else {
					return true;
				}
			}
		},
		methods: { //函数
			tabClick:function () {
				this.roleStatus = 'in';
			},
			handleClickPowerTree(row) {
				this.powerid = row.id;
				this.getNoRolePowerData();
			},
			handleClick(data, node) {
				this.msg = data;
				this.roleKey = data.role_key;
				this.roleName = data.role_name;
				this.getRoleUserData();
			},
			filterNode(value, data) {
				if(!value) return true;
				return data.title.indexOf(value) !== -1;
			},
			handleClose() {
				this.checkedUser = [];
				this.roleStatus = 'in';
			},

			rowClick(row, event, column) {
				this.toggleSelection(row);
			},
			toggleSelection(rows) {
				if(this.multipleTable.length > 0) {
					this.$refs.multipleTable.clearSelection();
				}
				this.$refs.multipleTable.toggleRowSelection(rows);
			},

			showdata: function() { //查询数据
				//显示数据
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'role_name', '');
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_role', jsonparas);
				query(_paras).then(response => {
					var json_data = response.result;
					this.roleDate = json_data;
					this.$notify({
						title: '成功信息',
						message: '数据加载完毕！',
						type: 'success'
					});
				});
			},
			//新增
			showAdd: function() { //显示新增对话框
				this.addFormVisible = true;
				this.text = '新增';
				this.isEditShow = false;
				this.addForm = {
					role_id: '',
					role_name: '',
					remarks: ''
				}
			},

			//获取权限树节点数据
			showPowerTreeData() {
				//显示数据
				let jsonparas = [];
				let paras = apiparas.getParas_rtype('default', 'basic|get_power_tree', 3, jsonparas);
				query(paras).then(response => {
					var json_data = response.result;
					this.PowerTreeData = json_data;
				});
			},
			
			//增加权限界面权限列表
			handleSelectionChange(val) {
				this.multipleTable = val;
			},
			//编辑
			showEdit: function(index, row) {
				this.addFormVisible = true;
				this.text = '编辑';
				//this.addForm = row;
				this.addForm.department_id = row.department_id;
				this.addForm.department_name = row.department_name;
				this.addForm.remarks = row.remarks;
				this.editId = row.department_key;
				this.isEditShow = true;
			},
			getRoleUserData: function() {
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'role_key', this.roleKey);
				apiparas.pushPara(jsonparas, 'type', 'in');
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_role_user', jsonparas);
				query(_paras).then(response => {
					this.roleUserData = response.result;
				});
			},
			getNoRoleUserData: function() {
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'role_key', this.roleKey);
				apiparas.pushPara(jsonparas, 'type', 'not in');
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_role_user', jsonparas);
				query(_paras).then(response => {
					this.noRoleUserData = response.result;
				});
			},
			getRolePowerData: function() {
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'role_key', this.roleKey);
				apiparas.pushPara(jsonparas, 'power_tree_key', this.powerid);
				apiparas.pushPara(jsonparas, 'type', 'in');
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_role_power', jsonparas);
				query(_paras).then(response => {
					this.rolePowerData = response.result;

				});
			},
			getNoRolePowerData: function() {
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'role_key', this.roleKey);
				apiparas.pushPara(jsonparas, 'power_tree_key', this.powerid);
				apiparas.pushPara(jsonparas, 'type', 'not in');
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_role_power', jsonparas);
				query(_paras).then(response => {
					this.noRolePowerData = response.result;
				});
			},
			//添加用户
			showAddUser: function() {
				this.addUserVisible = true;
				this.getNoRoleUserData();
			},
			//确定添加角色成员
			addUser: function() {
				let str = '';
				for(let i = 0; i < this.checkedUser.length; i++) {
					str = str + this.checkedUser[i] + ','
				}
				str = str.substring(0, str.length - 1);
				var jsonparas = [];
				apiparas.pushPara(jsonparas, 'user_keys', str);
				apiparas.pushPara(jsonparas, 'role_keys', this.roleKey);
				let _paras = apiparas.getParas('default', 'basic|insert_role_user', jsonparas);
				execute(_paras).then(response => {
					this.addUserVisible = false;
					this.checkedUser = [];
					if(response.errid == 0) {
						this.$notify({
							title: '添加',message: '成功添加',type: 'success'
						});
						this.getRoleUserData();
					} else {
						this.$notify.error({
							title: '错误',message: response.errmsg
						});
					}
				});
			},
			delUser: function() {
				var keys = '';
				for(var i = 0; i < this.checkedUser.length; i++) {
					keys += this.checkedUser[i] + ",";
				}
				if(keys == '') {
					this.$notify({
						title: '信息提示',message: '请选择要删除的明细！',type: 'info'
					});
					return;
				}
				keys = keys.substring(0, keys.length - 1);
				this.$confirm('是否确定删除选中成员?', '提示', {
					confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'
				}).then(() => {
					var jsonparas = [];
					apiparas.pushPara(jsonparas, 'keys', keys);
					apiparas.pushPara(jsonparas, 'role_key', this.roleKey);
					let _paras = apiparas.getParas('default', 'basic|del_role_user', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0) {
							this.$notify({
								title: '添加',message: '删除成功',type: 'success'
							});
							this.checkedUser = [];
							this.getRoleUserData();
						} else {
							this.$notify.error({
								title: '错误',message: '删除失败'
							});
						}
					});
				}).catch(() => {
					this.$message({
						type: 'info',message: '已取消添加'
					});
				});
			},

			showAddPower: function() {
				this.addPowerVisible = true;
				this.roleStatus = 'not in';
			},
			
			delPower: function() {
				var keys = '';
				for(var i = 0; i < this.multipleTable.length; i++) {
					keys += this.multipleTable[i].power_key + ",";
				}
				if(keys == '') {
					this.$notify({
						title: '信息提示',message: '请选择要删除的明细！',type: 'info'
					});
					return;
				}
				keys = keys.substring(0, keys.length - 1);
				this.$confirm('是否确定删除选中权限?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					var jsonparas = [];
					apiparas.pushPara(jsonparas, 'keys', keys);
					apiparas.pushPara(jsonparas, 'role_key', this.roleKey);
					let _paras = apiparas.getParas('default', 'basic|del_role_power', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0) {
							this.$notify({
								title: '添加',message: '删除成功',type: 'success'
							});
							this.rolePowerData = [];
							this.multipleTable = [];
							this.delstatus = true;
						} else {
							this.$notify.error({
								title: '错误',message: '删除失败'
							});
						}
					});
				}).catch(() => {
					this.$message({
						type: 'info',message: '已取消添加'
					});
				});
			},
			addSubmit: function() { //提交
				if(this.isEditShow) {
					//增加查询条件
					let jsonparas = [
					{'name': 'department_key','value': this.editId},
					{'name': 'department_id','value': this.addForm.department_id},
					{'name': 'department_name','value': this.addForm.department_name},
					{'name': 'remarks','value': this.addForm.remarks}
					]
					//查询汇总
					let _paras = apiparas.getParas('default', 'basic|update_department', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0) {
							this.addFormVisible = false;
							this.$notify({
								title: '成功信息',message: '修改成功！',type: 'success'
							});
							this.showdata();
						} else {
							this.$notify.error({
								title: '错误',message: response.errmsg
							});
						}
					});
				} else {
					//处理添加
					//增加查询条件
					let jsonparas = [
					{'name': 'role_id','value': this.addForm.role_id},
					{'name': 'role_name','value': this.addForm.role_name},
					{'name': 'remarks','value': this.addForm.remarks}
					];
					//查询汇总
					let _paras = apiparas.getParas('default', 'basic|insert_role', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0) {
							this.addFormVisible = false;
							this.$notify({
								title: '成功信息',message: '添加成功！',type: 'success'
							});
							this.showdata();
						} else {
							this.$notify.error({
								title: '错误',message: response.errmsg
							});
						}
					});
				}
			},
			resetForm: function(formName) { //重置
				this.$refs[formName].resetFields();
			},
			//删除
			showDel: function() {
				if(this.roleUserData.length === 0) {
					this.$confirm('此操作将永久删除 '+this.roleName+'  角色, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						var jsonparas = [];
						apiparas.pushPara(jsonparas, 'role_key', this.roleKey);
						let _paras = apiparas.getParas('default', 'basic|del_role', jsonparas);
						execute(_paras).then(response => {
							var json_data = response.result;
							if(response.errid == 0) {
								this.$notify({
									title: '删除',message: '成功删除数据',type: 'success'
								});
								this.rolePowerData=[]
								this.showdata();
							} else {
								this.$notify.error({
									title: '错误',message: response.errmsg
								});
							}
						});
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						});
					});
				} else {
					this.$message.error('您要删除的角色下有成员！');
				}
			},
			showExport: function() //导出
			{
				this.downloadLoading = true
				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require('@../../vendor/Export2Excel')
					const tHeader = ['部门ID', '部门名称', '部门说明', '创建时间', '修改时间'];
					const filterVal = ['department_id', 'department_name', 'remarks', 'create_time', 'update_time'];
					const list = this.roleDate;
					const _data = this.formatJson(filterVal, list);
					export_json_to_excel(tHeader, _data, '部门管理');
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			},
			tableRowClassName(row, rowIndex) {
				return '';
			},
			handleSizeChange: function(size) {
				this.pagesize = size;
			},
			handleCurrentChange: function(currentPage) {
				this.currentPage = currentPage;
			},
			getAddPowerVisible(val){
				this.addPowerVisible = val;
			},
			getMultipleTable(val2){
				this.multipleTable = val2;
			},
			getDelStatus(val){
				this.delstatus = val;
			}
		},
		created: function() {
			this.showdata();
		},
		watch: {
			filterText(val) {
				this.$refs.tree.filter(val);
			}
		}
	}
</script>

<style>
	.setheight_scroller {
		height: 500px;
		overflow: auto;
	}
	.setheight_scroller1 {
		height: 200px;
		overflow: auto;
	}
	.custom-tree-node {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 14px;
		padding-right: 8px;
	}
</style>